import React, { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Row, Col, List, Tag, Statistic, Spin, Button, Alert, Timeline } from 'antd';
import { ArrowUpOutlined, ArrowDownOutlined, AlertOutlined, HeartOutlined, AreaChartOutlined } from '@ant-design/icons';
import { useAuth } from '../../contexts/AuthContext';
import { iotService } from '../../services/iotService';
// 内联类型定义，避免导入问题
interface PatientDevice {
  deviceId: string;
  name: string;
  type: string;
  status: 'online' | 'offline' | 'low_battery' | 'error';
  lastConnected: number;
  batteryLevel: number;
  firmwareVersion: string;
  sensors: string[];
  location?: string;
  isActive: boolean;
}

interface RealTimeMonitoringData {
  patientId: string;
  deviceId: string;
  timestamp: number;
  vitalSigns: {
    heartRate?: number;
    bloodPressure?: {
      systolic: number;
      diastolic: number;
    };
    temperature?: number;
  };
  movementData?: {
    acceleration: number[];
    gyroscope: number[];
    orientation: number[];
    rangeOfMotion?: number;
  };
  alerts?: {
    type: string;
    message: string;
    severity: 'low' | 'medium' | 'high';
  }[];
}

interface RehabilitationData {
  sessionId: string;
  patientId: string;
  startTime: number;
  endTime: number;
  deviceId: string;
  exercises: {
    name: string;
    duration: number;
    repetitions: number;
    rangeOfMotion?: {
      min: number;
      max: number;
      average: number;
    };
    accuracy?: number;
  }[];
  completionRate: number;
  feedback?: string;
}

const DeviceStatus = {
  ONLINE: 'online',
  OFFLINE: 'offline',
  LOW_BATTERY: 'low_battery',
  ERROR: 'error'
} as const;
import Layout from '../../components/Layout';

const { Title, Paragraph, Text } = Typography;

const DeviceMonitoring: React.FC = () => {
  const { user } = useAuth();
  const [devices, setDevices] = useState<PatientDevice[]>([]);
  const [selectedDevice, setSelectedDevice] = useState<PatientDevice | null>(null);
  const [realTimeData, setRealTimeData] = useState<RealTimeMonitoringData | null>(null);
  const [rehabRecords, setRehabRecords] = useState<RehabilitationData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [unsubscribe, setUnsubscribe] = useState<() => void | null>(null);

  // 获取设备列表
  const fetchDevices = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const patientId = user?.id || 'patient-001';
      const deviceList = await iotService.getPatientDevices(patientId);
      setDevices(deviceList);
      
      // 自动选择第一个在线设备
      const onlineDevice = deviceList.find(device => device.status === DeviceStatus.ONLINE);
      if (onlineDevice) {
        setSelectedDevice(onlineDevice);
      }
    } catch (err) {
      setError('获取设备列表失败');
      console.error('Error fetching devices:', err);
    } finally {
      setLoading(false);
    }
  }, [user]);

  // 获取实时数据
  const fetchRealTimeData = useCallback(async (deviceId: string) => {
    try {
      const data = await iotService.getDeviceRealTimeData(deviceId);
      setRealTimeData(data);
    } catch (err) {
      console.error('Error fetching real-time data:', err);
    }
  }, []);

  // 获取康复记录
  const fetchRehabRecords = useCallback(async (deviceId?: string) => {
    try {
      const patientId = user?.id || 'patient-001';
      const records = await iotService.getRehabilitationRecords(patientId, deviceId);
      setRehabRecords(records);
    } catch (err) {
      console.error('Error fetching rehabilitation records:', err);
    }
  }, [user]);

  // 订阅实时数据更新
  useEffect(() => {
    if (selectedDevice) {
      // 取消之前的订阅
      if (unsubscribe) {
        unsubscribe();
      }
      
      // 订阅新设备的数据
      const unsub = iotService.subscribeToDeviceUpdates(
        selectedDevice.deviceId,
        (data) => setRealTimeData(data)
      );
      setUnsubscribe(unsub);
      
      // 获取当前实时数据
      fetchRealTimeData(selectedDevice.deviceId);
      // 获取康复记录
      fetchRehabRecords(selectedDevice.deviceId);
    }

    return () => {
      if (unsubscribe) {
        unsubscribe();
      }
    };
  }, [selectedDevice, fetchRealTimeData, fetchRehabRecords]);

  // 初始加载设备列表
  useEffect(() => {
    fetchDevices();
  }, [fetchDevices]);

  // 获取设备状态标签颜色
  const getDeviceStatusColor = (status: DeviceStatus) => {
    switch (status) {
      case DeviceStatus.ONLINE:
        return 'green';
      case DeviceStatus.OFFLINE:
        return 'default';
      case DeviceStatus.LOW_BATTERY:
        return 'orange';
      case DeviceStatus.ERROR:
        return 'red';
      default:
        return 'default';
    }
  };

  // 获取设备状态文本
  const getDeviceStatusText = (status: DeviceStatus) => {
    switch (status) {
      case DeviceStatus.ONLINE:
        return '在线';
      case DeviceStatus.OFFLINE:
        return '离线';
      case DeviceStatus.LOW_BATTERY:
        return '低电量';
      case DeviceStatus.ERROR:
        return '异常';
      default:
        return '未知';
    }
  };

  // 格式化时间戳
  const formatTimestamp = (timestamp: number) => {
    return new Date(timestamp).toLocaleString('zh-CN');
  };

  // 发送设备指令
  const handleSendCommand = async (command: string) => {
    if (!selectedDevice) return;
    
    try {
      const result = await iotService.sendDeviceCommand(selectedDevice.deviceId, command);
      Alert.success(result.message);
    } catch (err) {
      Alert.error('发送命令失败');
    }
  };

  if (loading && devices.length === 0) {
    return (
      <Layout title="设备监控">
        <Card>
          <div style={{ textAlign: 'center', padding: '50px 0' }}>
            <Spin size="large" />
            <Paragraph style={{ marginTop: 16 }}>正在加载设备信息...</Paragraph>
          </div>
        </Card>
      </Layout>
    );
  }

  if (error) {
    return (
      <Layout title="设备监控">
        <Card>
          <Alert
            message="错误"
            description={error}
            type="error"
            showIcon
            action={
              <Button type="primary" size="small" onClick={fetchDevices}>
                重试
              </Button>
            }
          />
        </Card>
      </Layout>
    );
  }

  return (
    <Layout title="设备监控">
      <Row gutter={[16, 16]}>
        {/* 设备列表 */}
        <Col xs={24} lg={6}>
          <Card title="我的设备">
            <List
              itemLayout="horizontal"
              dataSource={devices}
              renderItem={(device) => (
                <List.Item
                  key={device.deviceId}
                  onClick={() => setSelectedDevice(device)}
                  style={{
                    cursor: 'pointer',
                    backgroundColor: selectedDevice?.deviceId === device.deviceId ? '#f0f7ff' : 'transparent',
                    borderLeft: selectedDevice?.deviceId === device.deviceId ? '3px solid #1890ff' : '3px solid transparent',
                  }}
                >
                  <List.Item.Meta
                    title={
                      <div>
                        <Text strong>{device.name}</Text>
                        <Tag color={getDeviceStatusColor(device.status)} style={{ marginLeft: 8 }}>
                          {getDeviceStatusText(device.status)}
                        </Tag>
                      </div>
                    }
                    description={
                      <div>
                        <Text type="secondary">位置：{device.location}</Text>
                        <br />
                        <Text type="secondary">电量：{device.batteryLevel}%</Text>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>

        {/* 实时数据和控制面板 */}
        <Col xs={24} lg={18}>
          {selectedDevice ? (
            <Card title={`${selectedDevice.name} - 实时监控`}>
              {realTimeData ? (
                <div>
                  {/* 生命体征卡片 */}
                  <Row gutter={[16, 16]}>
                    <Col xs={24} sm={8}>
                      <Card>
                        <Statistic
                          title="心率"
                          value={realTimeData.vitalSigns.heartRate}
                          precision={0}
                          valueStyle={{ color: '#3f8600' }}
                          suffix="bpm"
                          prefix={<HeartOutlined />}
                        />
                      </Card>
                    </Col>
                    <Col xs={24} sm={8}>
                      <Card>
                        <Statistic
                          title="血压"
                          value={realTimeData.vitalSigns.bloodPressure?.systolic}
                          precision={0}
                          valueStyle={{ color: '#1890ff' }}
                          suffix={`/${realTimeData.vitalSigns.bloodPressure?.diastolic} mmHg`}
                        />
                      </Card>
                    </Col>
                    <Col xs={24} sm={8}>
                      <Card>
                        <Statistic
                          title="体温"
                          value={realTimeData.vitalSigns.temperature}
                          precision={1}
                          valueStyle={{ color: '#fa8c16' }}
                          suffix="°C"
                          prefix={<AreaChartOutlined />}
                        />
                      </Card>
                    </Col>
                  </Row>

                  {/* 运动数据 */}
                  {realTimeData.movementData && (
                    <Card title="运动数据" style={{ marginTop: 16 }}>
                      <Row gutter={[16, 16]}>
                        <Col xs={24} md={8}>
                          <Text>活动范围: </Text>
                          <Text strong>{realTimeData.movementData.rangeOfMotion?.toFixed(1)}°</Text>
                        </Col>
                        <Col xs={24} md={16}>
                          <Text>加速度: </Text>
                          <Text strong>
                            [{realTimeData.movementData.acceleration.map(a => a.toFixed(2)).join(', ')}]
                          </Text>
                        </Col>
                      </Row>
                    </Card>
                  )}

                  {/* 警报信息 */}
                  {realTimeData.alerts && realTimeData.alerts.length > 0 && (
                    <Alert
                      message="警报信息"
                      description={
                        <Timeline>
                          {realTimeData.alerts.map((alert, index) => (
                            <Timeline.Item key={index} color={
                              alert.severity === 'high' ? 'red' :
                              alert.severity === 'medium' ? 'orange' : 'blue'
                            }>
                              {alert.message}
                            </Timeline.Item>
                          ))}
                        </Timeline>
                      }
                      type="warning"
                      showIcon
                      style={{ marginTop: 16 }}
                    />
                  )}

                  {/* 设备控制按钮 */}
                  <div style={{ marginTop: 24, textAlign: 'center' }}>
                    <Row gutter={[16, 16]} justify="center">
                      <Col>
                        <Button 
                          type="primary" 
                          onClick={() => handleSendCommand('start_monitoring')}
                          disabled={selectedDevice.status !== DeviceStatus.ONLINE}
                        >
                          开始监控
                        </Button>
                      </Col>
                      <Col>
                        <Button 
                          onClick={() => handleSendCommand('stop_monitoring')}
                          disabled={selectedDevice.status !== DeviceStatus.ONLINE}
                        >
                          停止监控
                        </Button>
                      </Col>
                      <Col>
                        <Button 
                          danger 
                          onClick={() => handleSendCommand('reset_device')}
                          disabled={selectedDevice.status !== DeviceStatus.ONLINE}
                        >
                          重置设备
                        </Button>
                      </Col>
                    </Row>
                  </div>

                  <Text type="secondary" style={{ display: 'block', textAlign: 'right', marginTop: 16 }}>
                    最后更新: {formatTimestamp(realTimeData.timestamp)}
                  </Text>
                </div>
              ) : (
                <Spin size="large" />
              )}
            </Card>
          ) : (
            <Card>
              <Alert
                message="请选择设备"
                description="从左侧设备列表中选择一个设备查看详细信息"
                type="info"
                showIcon
              />
            </Card>
          )}

          {/* 康复训练记录 */}
          {rehabRecords.length > 0 && (
            <Card title="康复训练记录" style={{ marginTop: 16 }}>
              <List
                dataSource={rehabRecords}
                renderItem={(record) => (
                  <List.Item>
                    <List.Item.Meta
                      title={`训练时间: ${formatTimestamp(record.startTime)}`}
                      description={
                        <div>
                          <Paragraph>持续时间: {(record.endTime - record.startTime) / 60000} 分钟</Paragraph>
                          <Paragraph>完成率: {Math.round(record.completionRate * 100)}%</Paragraph>
                          {record.feedback && (
                            <Paragraph type="secondary">医生反馈: {record.feedback}</Paragraph>
                          )}
                          <List
                            dataSource={record.exercises}
                            renderItem={(exercise) => (
                              <List.Item>
                                <Text strong>{exercise.name}</Text>
                                <Text type="secondary" style={{ marginLeft: 16 }}>
                                  {exercise.repetitions} 次 · {exercise.duration / 1000} 秒
                                </Text>
                              </List.Item>
                            )}
                          />
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          )}
        </Col>
      </Row>
    </Layout>
  );
};

export default DeviceMonitoring;